package lock;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/*
HashMap线程不安全的演示以及解决方案
 */
public class ThreadDemo6 {

  public static void main(String[] args) {

//    HashMap<String, String> map = new HashMap<>();
//    解决：1.使用ConcurrentHashMap 2.使用Collections下的synchronizedMap
//    Map<String, String> map = new ConcurrentHashMap<>();
    Map<String, String> map = Collections.synchronizedMap(new HashMap<>());


    for (int i = 0; i < 30; i++) {
      String key = String.valueOf(i);

      new Thread(() -> {

        map.put(key, UUID.randomUUID().toString().substring(0,8));
        System.out.println(map);

      },String.valueOf(i)).start();

    }

  }
}
